package com.willian.andrappfw.utils;

import android.content.SharedPreferences;
import android.text.TextUtils;

import androidx.preference.PreferenceManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;


public class WPreferenceManager {
    private static SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Utils.getApplicationContext());


    public static SharedPreferences getInstance() {
        return sp;
    }

    public static String getToken() {
        return getInstance().getString(PreferenceKeys.TOKEN, "");
    }

    public static int getUserId() {
        return getInstance().getInt(PreferenceKeys.USER_ID, 0);
    }

    public static void removeToken() {
        getInstance().edit().remove(PreferenceKeys.TOKEN).remove(PreferenceKeys.USER_ID).apply();
    }

    public static void saveAsJson(String key, Object obj) {
        getInstance().edit().putString(key, new Gson().toJson(obj)).apply();
    }

    public static <T> List<T> getListFromJson(String key, Class<T> itemClass) {
        List<T> lst = new ArrayList<>();
        String banners = getInstance().getString(key, null);
        if (TextUtils.isEmpty(banners)) {
            return lst;
        }

        try {
            JsonArray array = new JsonParser().parse(banners).getAsJsonArray();
            for (final JsonElement elem : array) {
                lst.add(new Gson().fromJson(elem, itemClass));
            }
        } catch (Exception ignored) {
        }
        return lst;
    }

    public static <T> T getObjectFromJson(String key, Class<T> objClass) {
        String banners = getInstance().getString(key, null);
        if (TextUtils.isEmpty(banners)) {
            return null;
        }
        return new Gson().fromJson(banners, objClass);
    }
}
